package src.leetcode.lcsaf.mid_2516;

public class takeCharacters {
    public static void main(String[] args) {
        System.out.println(new Solution().takeCharacters("aabaaaacaabc", 2));
    }
}

class Solution {
    public int takeCharacters(String s, int k) {
        int[] count = new int[3];
        int n = s.length();
        for (int i = 0; i < n; i++) {
            count[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < 3; i++) {
            count[i] -= k;
            if (count[i] < 0) return -1;
        }

        int left = 0, right = 0;
        int ans = 0;
        while (right < n && left < n) {
            int index = s.charAt(right) - 'a';
            if (count[index] > 0) {
                count[s.charAt(right++) - 'a']--;
            } else {
                count[s.charAt(left++) - 'a']++;
            }

            if (count[index] >= 0) {
                ans = Math.max(ans, right - left);
            }
        }
        return n - ans;
    }
}